/*
 * StockFacadeBean.java
 *
 * Created on 8 May 2007, 01:53
 * Copyright (C) 2007   Yuezhong Zhang
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package usyd.comp5348;

import java.util.Collection;
import java.util.LinkedList;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Yuezhong Zhang   305375638
 * @sicne version 2.0 for assignemnt 2
 *
 */
@Stateless(mappedName="ejb/Stock")
public class StockFacadeBean implements StockFacadeRemote, StockFacadeLocal {
    private Logger logger = Logger.getLogger("usyd.comp5438.StockFacadeBean");
    @PersistenceContext
    private EntityManager em;
    
    /** Creates a new instance of StockFacadeBean */
    public StockFacadeBean() {
    }
    /**
     * Create a new item
     *@param stock stock information, cannot be null
     *@return id the newly created stock id
     */
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public int createItem(Stock stock) {
        em.persist(stock);
        em.flush();
        return stock.getId();
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void modifyItem(Stock stock)throws StockException {
        Stock s = em.find(Stock.class, stock.getId());
        if(s == null) {
            StockException sex = new StockException("Couldn't find stock with id="+stock.getId());
            logger.warning(sex.getMessage());
            throw sex;
        }
        s.setCatalogueId(stock.getCatalogueId());
        s.setHolding(stock.getHolding());
        s.setWarehouse(stock.getWarehouse());
        em.merge(s);
        em.flush();
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void deleteItem(int id) {
        Stock s = em.find(Stock.class, id);
        if(s !=null) {
            em.remove(s);
            em.flush();
        }
        
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public int sold(int catalogueId, int quantity, String warehouse)throws StockException {
        Query query = em.createNamedQuery("queryHoldingByCatalogueIDAndWarehouse");
        query.setParameter("warehouse",warehouse);
        query.setParameter("catalogueId",catalogueId);
        Stock s = (Stock) query.getSingleResult();
        if( s == null){
            StockException se = new StockException("Couldn't find stock for catalogueId="+ catalogueId +" warehouse="+ warehouse);
            logger.warning(se.getMessage());
            throw se;
        }
        if(s.getHolding() < quantity) {
            //we cannot sell this quantity
            StockException se = new StockException("Attempt to sell("+quantity+")more goods than held("+s.getHolding()+")in stock");
            logger.warning(se.getMessage());
            throw se;
        }
        s.setHolding( s.getHolding() - quantity);
        em.merge(s);
        em.flush();
        return s.getHolding();
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public int bought(int catalogueId, int quantity, String warehouse) throws StockException{
        Query query = em.createNamedQuery("queryHoldingByCatalogueIDAndWarehouse");
        query.setParameter("warehouse",warehouse);
        query.setParameter("catalogueId",catalogueId);
        Stock s = (Stock) query.getSingleResult();
        if( s == null){
            StockException se = new StockException("Couldn't find stock for catalogueId="+ catalogueId +" warehouse="+ warehouse);
            logger.warning(se.getMessage());
            throw se;
        }
        s.setHolding( s.getHolding() + quantity);
        em.merge(s);
        em.flush();
        return s.getHolding();
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public Stock getItemById(int id) {
        return em.find(Stock.class, id);
        
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public Collection<Stock> getItemByWarehouse(String warehouse) {
        Collection<Stock> items  = new  LinkedList<Stock>();
        Query query = em.createNamedQuery("queryItemByWarehouse");
        query.setParameter("warehouse", warehouse);
        for(Object obj : query.getResultList()){
            if(obj instanceof Stock){
                items.add((Stock)obj);
            }
        }
        return items;
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public int getHoldingByWarehouse(int catalogueId, String warehouse) throws StockException{
        Query query = em.createNamedQuery("queryHoldingByCatalogueIDAndWarehouse");
        query.setParameter("warehouse",warehouse);
        query.setParameter("catalogueId",catalogueId);
        Stock s = (Stock) query.getSingleResult();
        if( s == null){
            StockException se = new StockException("Couldn't find stock for catalogueId="+ catalogueId +" warehouse="+ warehouse);
            logger.warning(se.getMessage());
            throw se;
        }
        return s.getHolding();
    }
}
